package com.example.springbootsfzy.controller.liujinping;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import com.example.springbootsfzy.util.OSSUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import static org.springframework.boot.Banner.Mode.LOG;

@RestController
@RequestMapping("/stream")
public class StreamController {
    @RequestMapping(path = { "/stream-video-file" }, method = RequestMethod.GET)
    public ResponseEntity<StreamingResponseBody> streamFile(
            HttpServletRequest request,
            HttpServletResponse response) {
        File file = new File("/path/to/file.mp4");
        if (!file.isFile()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        StreamingResponseBody stream = out -> {
            try {
                final InputStream inputStream = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = inputStream.read(bytes)) >= 0) {
                    out.write(bytes, 0, length);
                }
                inputStream.close();
                out.flush();
            } catch (final Exception e) {
                System.out.println("Exception while reading and streaming data {} "+ e);
            }
        };
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "video/mp4");
        headers.add("Content-Length", Long.toString(file.length()));
        return ResponseEntity.ok().headers(headers).body(stream);
    }

    @PostMapping("/upload")
    public  String   upload(MultipartFile file) throws IOException {

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新的文件名（唯一性）
        String fileName = UUID.randomUUID().toString() + suffix;

        // 上传文件
        String url = OSSUtil.upload(fileName, file.getInputStream());

        return url;
    }
    @GetMapping("/download2")
    public  void   download2(String fileName, HttpServletResponse  response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        response.setContentType("application/octet-stream");
        ServletOutputStream out = response.getOutputStream();
        OSSUtil.download(fileName,out);
    }


}